#include "HttpResponse.h"

// 实例化HttpResponse
HttpResponse::HttpResponse() {
	_statusCode = StatusCode::UnKnow;
	_headers.clear();
	_fileName = string();
	_sendDataFunc = nullptr;
}

// 销毁HttpResponse
HttpResponse::~HttpResponse() {}

// 添加响应头键值对到response
void HttpResponse::addHeader(const string key, const string value) {
	if (key == string() || value == string()) { return; }
	_headers.insert(make_pair(key, value));
}

// 构建Http响应，并发送到sendBuf
void HttpResponse::prespareMsg(Buffer* sendBuf, int sockfd) {
	// 1. 状态行
	char tmp[1024];
	int code = static_cast<int>(_statusCode);
	sprintf(tmp, "HTTP/1.1 %d %s\r\n", code, _info[code].data());
	sendBuf->appendString(tmp);

	// 2. 响应报头
	for (auto it = _headers.begin(); it != _headers.end(); ++it) {
		sprintf(tmp, "%s: %s\r\n", it->first.data(), it->second.data());
		sendBuf->appendString(tmp);
	}

	// 3. 空行
	sendBuf->appendString("\r\n");
#ifndef MSG_SEND_AUTO
	sendBuf->sendData(sockfd); // 将sendBuf中的数据发送出去
#endif

	// 4. 回复的数据
	_sendDataFunc(_fileName, sendBuf, sockfd);
}